<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>菜单管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体内容 -->
    <el-row>
      <!-- title -->
      <div class="modt-box">菜单管理</div>
      <el-col :span="4"></el-col>
      <el-col :span="6">
        <el-tree class="treeclass" ref="tree" :data="treeData" :props="defaultProps" :load="loadNode"
                 @node-click="nodeclick" @check-change="handleClick" node-key="id" lazy></el-tree>
      </el-col>
      <el-col :span="18">
        <div class="mod-btnbox">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addModule">添加</el-button>
        </div>
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">

          <el-form-item label="父级菜单" prop="parentId">
            <el-select size="small" v-model="form.parentId" placeholder="请选择" class="selectw">
              <el-option label="一级菜单（根目录）" :value="0"></el-option>
              <el-option v-for="parm in fmenu" :key="parm.menuId" :label="parm.name" :value="parm.menuId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="菜单名称" prop="moduleName">
            <el-input size="small" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="图标" prop="icon">
            <el-input size="small" v-model="form.icon"></el-input>
          </el-form-item>
          <el-form-item label="权限" prop="perms">
            <el-input size="small" v-model="form.perms"></el-input>
          </el-form-item>
          <el-form-item label="URL" prop="url">
            <el-input size="small" v-model="form.url"></el-input>
          </el-form-item>
          <el-form-item label="顺序" prop="orderNum">
            <el-input-number size="small" :min="1" v-model="form.orderNum"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="saveModule('form')">保存</el-button>
            <el-button size="small" type="primary" v-show="showdelete" @click="deleteModule">删除</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {ModuleDelete, ModuleGet, ModuleNodes, ModuleSave, ModuleUpdate} from '../../api/userMG'

export default {
  data() {
    return {
      showdelete: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      form: {
        menuId: '',
        parentId: '',
        name: '',
        url: '',
        perms: '',
        type: '',
        icon: '',
        orderNum: ''
      },
      // rules表单验证
      rules: {
        parentId: [
          {required: true, message: '请选择父级菜单', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入菜单名称', trigger: 'blur'}
        ],
        icon: [
          {required: true, message: '请输入菜单图标', trigger: 'blur'}
        ],
        url: [{required: true, message: '请输入URL', trigger: 'blur'}],
        orderNum: [
          {required: true, message: '请输入菜单顺序', trigger: 'blur'}
        ]
      },
      fmenu: [{id: 1, name: "平台顶级"}]
    }
  },
  /**
   * 创建完毕
   */

  created() {
    this.getdata();
    this.treeData = [];
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    loadNode(node, resolve) {
      console.log(node.data.id);

      console.log(node.data.id===undefined ? 0 : node.data.id)
      ModuleNodes({
        "page": 1,
        "perPage": 100,
        "filters": [
          {
            "placeholder": "",
            "fieldName": "parentId",
            "compare": "=",
            "fieldValue": node.data.id===undefined ? 0: node.data.id
          }
        ],
        "isLock": "",
        "orderBy": "order_num asc"
      })
        .then(res => {
          if (node.level > 1) return resolve([]);
          const subMenus = [];
          for (const item of res.data.list) {
            subMenus.push({
              id: item.menuId,
              pid: item.parentId,
              name: item.name,
              leaf: true
            })
          }
          resolve(subMenus);
        })
        .catch(err => {
          console.error(err)
          this.loading = false;
          this.$message.error('用户管理获取失败，请稍后再试！')
        })
    },
    // 获取数据
    getdata() {
      // ModuleNodes({
      //   "page": 1,
      //   "perPage": 100,
      //   "filters": [
      //     {
      //       "placeholder": "",
      //       "fieldName": "parentId",
      //       "compare": "=",
      //       "fieldValue": "0"
      //     }
      //   ],
      //   "isLock": "",
      //   "orderBy": "order_num asc"
      // })
      //   .then(res => {
      //     if (res.data.list) {
      //       this.fmenu = res.data.list;
      //       this.treeData = [];
      //       console.log(11)
      //       for (const item of res.data.list) {
      //         console.log(this.treeData)
      //         this.treeData.push({
      //           id: item.menuId,
      //           pid: item.parentId,
      //           name: item.name,
      //           open: false,
      //           checked: false
      //         });
      //       }
      //     }
      //   })
      //   .catch(err => {
      //     this.loading = false;
      //     this.$message.error('菜单管理列表失败，请稍后再试！')
      //   })
    },
    // 添加
    addModule() {
      this.showdelete = false;
      this.form = {
        menuId: '',
        parentId: '',
        name: '',
        url: '',
        perms: '',
        type: '',
        icon: '',
        orderNum: ''
      }
    },
    // 获取父级菜单
    getmenu() {
      let parm = {
        page: '1',
        limit: '10'
      };
      ModuleNodes({
        "page": 1,
        "perPage": 100,
        "filters": [
          {
            "placeholder": "",
            "fieldName": "type",
            "compare": "=",
            "fieldValue": "0"
          }
        ]
      })
        .then(res => {
          this.fmenu = res.data.list;
        })
        .catch(err => {
          this.loading = false
          this.$message.error('父级菜单列表获取失败，请稍后再试！')
        })
    },
    // 复选变单选
    handleClick(data, checked, node) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([])
        this.$refs.tree.setCheckedNodes([data])
        this.showdelete = true
      } else {
      }
    },
    // 点击节点
    nodeclick(arr, node, self) {
      ModuleGet(arr.id)
        .then(res => {
          this.form = res.data;
          this.$refs.tree.setCheckedNodes([]);
          this.$refs.tree.setCheckedNodes([arr])
        })
        .catch(err => {
          console.error(err)
          this.loading = false;
          this.$message.error('用户管理获取失败，请稍后再试！')
        })
    },
    // 保存菜单
    saveModule(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          if(this.form.menuId) {
            ModuleUpdate(this.form)
              .then(res => {
                this.getdata()
              }).then(res => {
              this.getdata()
              this.$message.success('菜单管理列表删除成功！')
              this.showdelete = false;
              this.form = {
                menuId: '',
                parentId: '',
                name: '',
                url: '',
                perms: '',
                type: '',
                icon: '',
                orderNum: ''
              }
            })
              .catch(err => {
                this.$message.error('菜单管理列表保存失败，请稍后再试！')
              })
          } else {
            ModuleSave(this.form)
              .then(res => {
                this.getdata()
              }).then(res => {
              this.getdata()
              this.$message.success('菜单管理列表删除成功！')
              this.showdelete = false;
              this.form = {
                menuId: '',
                parentId: '',
                name: '',
                url: '',
                perms: '',
                type: '',
                icon: '',
                orderNum: ''
              }
            })
              .catch(err => {
                this.$message.error('菜单管理列表保存失败，请稍后再试！')
              })
          }
        } else {
          return false
        }
      })
    },
    // 删除菜单
    deleteModule() {
      ModuleDelete(this.form.menuId)
        .then(res => {
          this.getdata()
          this.$message.success('菜单管理列表删除成功！')
          this.showdelete = false;
          this.form = {
            menuId: '',
            parentId: '',
            name: '',
            url: '',
            perms: '',
            type: '',
            icon: '',
            orderNum: ''
          }
        })
        .catch(err => {
          this.$message.error('菜单管理列表删除失败，请稍后再试！')
        })
    }
  }
}
</script>

<style>
.user-search {
  margin-top: 20px !important;
}

.user-search td {
  margin-top: 20px !important;
}

.userRole {
  width: 100%;
}

.el-table__expanded-cell {
  padding: 0px !important;
  margin: 0px !important;
}

.modt-box {
  width: 100%;
  height: 60px;
  line-height: 60px;
  background-color: #f0f2f5;
  text-align: center;
  color: #334157;
  margin-top: 20px;
  margin-bottom: 20px;
  font-size: 24px;
}

.mod-btnbox {
  margin-bottom: 20px;
}

.treeclass {
  border: 1px solid #f3f3f3;
  padding-top: 20px;
  padding-bottom: 20px;
}

.selectw {
  width: 100%;
}
</style>

